package com.ruoyi.web.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.novel.domain.Invitation;
import com.ruoyi.novel.domain.User;
import com.ruoyi.novel.service.IInvitationService;
import com.ruoyi.novel.service.IUserService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * APP登录相关
 */

@RestController
@RequestMapping("/app")
public class AppLoginController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IInvitationService invitationService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(loginBody.getUsername());
        if(sysUserService.checkUserNameUnique(sysUser)){
            RegisterBody body = new RegisterBody();
            body.setUsername(loginBody.getUsername());
            body.setPassword(loginBody.getPassword());
            AjaxResult result = userService.register(body);
            if((boolean) result.get("regFlag")){
                sysUser = (SysUser) result.get("sysUser");
                User user = new User();
                user.setId(Math.toIntExact(sysUser.getUserId()));
                user.setPhone(body.getUsername());
                user.setLevelTime(new Date());
                userService.insertUser(user);
            }else {
                return AjaxResult.error((String) result.get("msg"));
            }
        }
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.loginNotCode(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody body)
    {
        AjaxResult result = userService.register(body);
        if((boolean) result.get("regFlag")){
            SysUser sysUser = (SysUser) result.get("sysUser");
            User user = new User();
            List<Invitation> invitationList = invitationService.list(new QueryWrapper<Invitation>().eq("code", body.getCode()).eq("state",0));
            if(!invitationList.isEmpty()){
                Invitation invitation = invitationList.get(0);
                User u = userService.getById(invitation.getUserId());
                if(u != null){
                    List<String> list = new ArrayList<>();
                    list.addAll(Arrays.asList(u.getAncestors().split(",")));
                    String id = String.valueOf(u.getId());
                    if(list.isEmpty() || list == null){
                        list = new ArrayList<>();
                        list.add("0");
                        list.add(id);
                    }else {
                        list.add(id);
                    }
                    String ancestors = String.join(",", list);
                    user.setReferrer(u.getId());
                    user.setAncestors(ancestors);
                }else {
                    user.setReferrer(0);
                }
            }
            user.setId(Math.toIntExact(sysUser.getUserId()));
            user.setPhone(body.getUsername());
            user.setLevelTime(new Date());
            return AjaxResult.success(userService.insertUser(user));
        }else {
            return AjaxResult.error((String) result.get("msg"));
        }
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        User user = userService.getById(loginUser.getUserId());

        tokenService.refreshToken(loginUser);

        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        return ajax;
    }
}
